package com.stu.shiro;

import com.stu.config.RedisUtils;
import com.stu.shiro.bean.SysUser;
import com.stu.shiro.service.ISysMenuService;
import com.stu.shiro.service.ISysRoleService;
import com.stu.shiro.service.ISysUserService;
import com.stu.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @author MI
 * @ClassName ShiroRealm.java
 * @createTime 2021年08月25日 15:23:00
 * 自定义 Realm 自定义实现 ，包含认知和授权
 */
@Slf4j
public class ShiroRealm extends AuthorizingRealm {
    @Resource
    private RedisUtils redisUtil;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysMenuService menuService;

    //必须重写，否则报错
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    //授权

    /**
     * 只有当需要检测用户权限的时候才会调用此方法
     * 授权模块，获取用户角色和权限。
     *
     * @param token token
     * @return AuthorizationInfo 权限信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection token) {
        System.out.println(StringUtils.center("获取权限集合", 51, "*"));
        // 这里的 token是从 JWTFilter 的 executeLogin 方法传递过来的，已经经过了解密|如果在 doGetAuthenticationInfo 方法中返回的是 new SimpleAuthenticationInfo(token, token, "febs_shiro_realm");
        //那么这里获取的是token
        // Integer userId = JWTUtil.getUserId(token.toString());

        // 如果在 doGetAuthenticationInfo 方法中返回的是 new SimpleAuthenticationInfo(user, token, "febs_shiro_realm"); 则获取的是 SysUser对象
        SysUser primaryPrincipal = (SysUser) token.getPrimaryPrincipal();

        Integer userId = primaryPrincipal.getId();

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        // 获取用户角色集
        Set<String> roleSet = roleService.selectRolePermissionByUserId(userId);
        simpleAuthorizationInfo.setRoles(roleSet);

        // 获取用户权限集
        Set<String> permissionSet = menuService.findUserPermissionsByUserId(userId);
        simpleAuthorizationInfo.setStringPermissions(permissionSet);
        return simpleAuthorizationInfo;
    }

    //认证

    /**
     * 用户认证:编写shiro判断逻辑，进行用户认证
     *
     * @param authenticationToken 身份认证 token
     * @return AuthenticationInfo 身份认证信息
     * @throws AuthenticationException 认证相关异常
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println(StringUtils.center("登录认证", 51, "*"));
        String token = (String) authenticationToken.getCredentials();
        String username = JWTUtil.getUsername(token); //从token中获取username
        Integer userId = JWTUtil.getUserId(token);    //从token中获取userId


        // 通过redis 查看token 是否过期
        String encryptTokenInRedis = redisUtil.get(Constant.RM_TOKEN_CACHE + username);
        if (!token.equalsIgnoreCase(encryptTokenInRedis)) {
            throw new AuthenticationException("token已经过期");
        }

        // 如果找不到，说明已经失效
        if (StringUtils.isBlank(encryptTokenInRedis)) {
            throw new AuthenticationException("token已经过期");
        }

        if (StringUtils.isBlank(username)) {
            throw new AuthenticationException("token校验不通过");
        }
        // 通过用户id查询用户信息
        SysUser user = userService.getById(userId);

        if (user == null) {
            throw new AuthenticationException("用户名或密码错误");
        }
        if (!JWTUtil.verify(token, username, user.getPassword())) {
            throw new AuthenticationException("token校验不通过");
        }
        //TODO
        // 设置 用户 ，以便可以 在其他位置通过  SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();取出
        return new SimpleAuthenticationInfo(user, token, "febs_shiro_realm");
    }

    public interface Constant {
        String RM_TOKEN_CACHE = "token:cache:";
    }
}


